// i.d(t, { l: () => SdkObservable, W: () => SdkObserver })
export class SdkObservable {
  dependencies: any
  subscriptionFactory: any
  observers: Set<any>
  currentData: any
  freshDataCache: any
  changeSubscription: any
  constructor(e, t, i) {
    ;(this.dependencies = e), (this.subscriptionFactory = t), (this.observers = new Set()), (this.currentData = i.create()), (this.freshDataCache = i.create())
  }
  static async create(e, t, i) {
    const n = await e.getDependencies()
    return new SdkObservable(n, t, i)
  }
  getData() {
    return this.currentData.data
  }
  subscribe(e) {
    return (
      this.addObserver(e),
      new (class ObserverSubscription {
        sdkObservable: any
        constructor(e) {
          ;(this.sdkObservable = e), this.renew()
        }
        renew() {
          this.sdkObservable.addObserver(e)
        }
        cancel() {
          this.sdkObservable.removeObserver(e)
        }
      })(this)
    )
  }
  addObserver(e) {
    if (!this.observers.has(e)) {
      class SdkObservableFacade {
        observable: any
        constructor(e) {
          this.observable = e
        }
        onChanged() {
          this.observable.onChanged()
        }
      }
      this.observers.add(e),
        1 === this.observers.size &&
          (this.currentData.update(...this.dependencies),
          (this.changeSubscription = this.subscriptionFactory.create(new SdkObservableFacade(this), ...this.dependencies))),
        (e.dirty = !0)
    }
  }
  removeObserver(e) {
    0 !== this.observers.size && (this.observers.delete(e), 0 === this.observers.size && this.changeSubscription.cancel())
  }
  onChanged() {
    if ((this.freshDataCache.update(...this.dependencies), !this.currentData.equals(this.freshDataCache))) {
      this.currentData.copy(this.freshDataCache)
      for (const e of this.observers) e.dirty = !0
    }
  }
}
export class SdkObserver {
  dirty: boolean
  constructor() {
    this.dirty = !1
  }
}
